<template>
  <el-upload
    :file-list="fileList"
    :accept="accept"
    ref="upload"
    :on-exceed="handleExceed"
    :auto-upload="false"
    :action="uploadUrl"
    :http-request="fnUploadRequest"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :on-error="handleError"
    drag
    :limit="limit"
    :disabled="disabled"
    :multiple="true">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <!--<div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div>-->
  </el-upload>
</template>
<script>

  import {getOssInfo,deleteFile} from '@/api/common';
  import OSS from 'ali-oss';

  export default {
    name: 'FILE_UPLOAD',
    props: {
      limit: {
        type: Number,
        required: false,
        default: 1
      },
      fileTypeArray: {
        type: Array,
        required: false,
        default: () => ['video/mp4']
      },
      accept: {
        type: String,
        required: false,
        default: 'video/*'
      },
      path: {
        type: String,
        require: false
      },
    },
    data() {
      return {
        uploadUrl: "",
        uploadFileLength: 0,
        uploadFileSuccess: 0,
        uploadFileNames: [],
        uploadFileName: [],
        fileList: [],
        disabled: false
      }
    },
    created() {
      console.log(this.path);
      if (this.path) {
        this.fileList = [{name: this.path, url: this.path}];
      }
      console.log('===>>');
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      beforeRemove(file, fileList) {
        console.log(file);
        if (file && file.status === "success") {
          return this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteFile(file.url);
            this.$emit('change', '');
          });
        } else {
          this.loadingClose();
        }
      },
      handleExceed(files, fileList) {
        //this.$message.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        fileList[0].name = files[0].name;
      },
      handleError(){
        this.$emit('change','error');
        this.loading.close();
      },
      async fnUploadRequest(option) {
        this.loading = this.$loading({
          lock: true,
          text: "上传文件中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });

        let file = option.file;
        let fileType = file.type;

        if (this.fileTypeArray.indexOf(fileType) === -1) {
          this.$message.error(`只接受文件类型为(${this.fileTypeArray.join(',')})`);
          return false;
        }

        this.disabled = true;
        let ossInfo = await getOssInfo();
        let client = new OSS({
          region: ossInfo.data.Region,
          accessKeyId: ossInfo.data.AccessKeyId,
          accessKeySecret: ossInfo.data.AccessKeySecret,
          stsToken: ossInfo.data.SecurityToken,
          bucket: ossInfo.data.BucketName
        });


        const point = file.name.lastIndexOf('.');
        let suffix = file.name.substr(point);
        let filename = ossInfo.data.FileUrl + suffix;

        let res;
        if (file.size < this.partSize) {
          res = await client.put(filename, file);
        } else {
          res = await client.multipartUpload(filename, file, {
            progress: async function (p) {
              let e = {};
              e.percent = p * 100;
              option.onProgress(e)
            }
          });
        }
        // 分片上传文件
        if (res.res.statusCode === 200) {
          this.$emit('change',ossInfo.data.FileHost + res.name);
          this.loading.close();
        } else {
          this.disabled = false;
          option.onError('上传失败');
        }
      }
    }
  }
</script>
